<template>
  <a-form
    ref="imageFormRef"
    :model="imageState"
    :labelCol="{ style: { width: '110px' } }"
    :colon="false"
    labelAlign="right"
    :rules="configRules"
  >
    <a-form-item label="上传图片体积" name="volume" class="form-item">
      <a-input v-model:value.number="imageState.volume" class="w-[148px]" suffix="KB" placeholder="请填写图片体积" />
    </a-form-item>
    <a-form-item label="上传图片类型" name="img_type" class="form-item">
      <a-checkbox-group v-model:value="imageState.img_type" :options="IMAGE_DATA" />
    </a-form-item>
  </a-form>
  <div class="page-btn">
    <a-button type="primary" :loading="loading" @click="saveImagePage">保存当前页面</a-button>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { configRules, IMAGE_DATA, IMAGE_TYPE } from '../state'
import apis from '@/apis'
import { message } from 'ant-design-vue'
import { storage } from '@/utils/storage'
import { getConversionLimit, unitConversion } from '@/utils/unitConversion'
const {
  system: { get_image_set, set_image_set }
} = apis
const imageFormRef = ref()
const loading = ref(false)
interface ImageState {
  volume: number | undefined
  img_type: number[]
}
const imageState = reactive<ImageState>({
  volume: undefined,
  img_type: []
})
const getImageSet = () => {
  get_image_set().then((res: any) => {
    console.log(res, '获取图片设置')
    Object.assign(imageState, res)
    res.img_type = res.img_type
      .map((item: number) => {
        return '.' + IMAGE_TYPE[item]
      })
      .join(' ')
    storage.set('img_type', res.img_type || [])
    storage.set('img_size', unitConversion(res.volume) || '')
    storage.set('img_size_limit', getConversionLimit(res.volume) || '')
  })
}
const saveImagePage = () => {
  imageFormRef.value
    .validate()
    .then(() => {
      loading.value = true
      set_image_set(imageState).then((res: any) => {
        message.success('图片设置保存成功')
        loading.value = false
        getImageSet()
      })
    })
    .catch(() => {
      loading.value = false
    })
}
defineExpose({ getImageSet })
</script>

<style lang="less" scoped>
.page-btn {
  border-top: 1px solid #e8e8e8;
  padding-top: 24px;
}
</style>
